package com.lds.config.center.client.listener.Annotation;

import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import lombok.Getter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.lang.reflect.Field;
import java.util.Objects;

public class DefaultItemChangeEventListenerBeanPostProcessor implements BeanPostProcessor {
    @Getter
    private static final Multimap<String, BeanField> beanFieldMap = LinkedListMultimap.create();

    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        Class<?> clazz = bean.getClass();

        ConfigurationProperties annotation = clazz.getAnnotation(ConfigurationProperties.class);
        if (Objects.isNull(annotation)) return bean;

        String prefix = annotation.prefix();
        if (StringUtils.isEmpty(prefix)) return bean;

        Field[] declaredFields = clazz.getDeclaredFields();
        if (ArrayUtils.isEmpty(declaredFields)) return bean;

        for (Field field : declaredFields) {
            String name = prefix + "." + field.getName();
            beanFieldMap.put(name, new BeanField(field.getName(), bean, field));
        }
        return bean;
    }

}
